package com.yonyou.pmclouds.login.controller;

import com.yonyou.pmclouds.basecom.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping(value = "/login")
public class LoginController {

	/**
	 * 验证用户名和密码
	 * 
	 * @param String
	 *            username,String password
	 * @return
	 */
	@RequestMapping(value = "/user")
	@ResponseBody
	public String checkLogin(@RequestParam(value="username", required=false) String username,@RequestParam(value="password", required=false)  String password,HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			UsernamePasswordToken token = new UsernamePasswordToken(username, SecurityUtil.EncoderByMd5(password));
			Subject currentUser = SecurityUtils.getSubject();
			if (!currentUser.isAuthenticated()) {
				// 使用shiro来验证
//				token.setRememberMe(true);
				currentUser.login(token);// 验证角色和权限
			}
		} catch (Exception ex) {
			log.error("登陆失败");
			return "error";
		}
		result.put("success", true);
		return "success";
	}

}
